package modes

import (
	"fmt"
	"time"
)

type CrmStuden struct {
	Id      int64  `json:"cstu_id" xorm:"id"`             // 学员ID
	Weight  int64  `json:"cstu_weight" xorm:"weight"`     // 权重
	Phone   string `json:"cstu_phone" xorm:"phone"`       // 手机号
	At      int64  `json:"cstu_at" xorm:"at"`             // 创建时间
	Amount  int64  `json:"cstu_amount" xorm:"amount"`     // 学院消费金额
	Name    string `json:"cstu_name" xorm:"name"`         // 学员姓名
	Senior  int64  `json:"cstu_senior" xorm:"senior"`     // 是否升级学员 1 不是， 0 是
	Uid     int64  `json:"cstu_uid" xorm:"uid"`           // 班长任ID
	Uname   string `json:"cstu_uname" xorm:"uname"`       // 班主任姓名
	Uat     int64  `json:"cstu_uat" xorm:"uat"`           // 分配版主人的时间
	OrderId int64  `json:"cstu_order_id" xorm:"order_id"` // 订单ID
	Cnumber int64  `json:"cstu_c_number" xorm:"c_number"` // 拨打次数
	Cat     int64  `json:"cstu_c_at" xorm:"c_at"`         // 最后一次拨打时间
	Note    string `json:"cstu_note" xorm:"note"`         // 备注
}

func (this *CrmStuden) TableName() string {
	return "crm_studen"
}
func (this *CrmStuden) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *CrmStuden) SutdenTo(order CrmOrder, fage int64, uid int64, name string, note string) error {
	this.Phone = order.Phone
	this.Amount = int64(order.RealPrice)
	this.Uid = uid
	this.Uname = name
	this.Note = note
	this.Senior = fage
	_, err := this.Save()
	return err
}

func (this *CrmStuden) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *CrmStuden) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *CrmStuden) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *CrmStuden) Count(where string) (int64, error) {
	var val CrmStuden
	return Db(0).Where(where).Count(&val)
}
func (this *CrmStuden) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *CrmStuden) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *CrmStuden) where(fage, count, page int, where, field string) ([]CrmStuden, error) {
	list := make([]CrmStuden, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *CrmStuden) List(val *Pager) error {
	val.TName = this.TableName()
	val.Total, _ = this.Count(val.ToWhere())
	list, err := this.where(val.Rules, val.Count, val.Page-1, val.ToWhere(), "")
	if err == nil {
		val.List = list
	}
	return err
}

func (this *CrmStuden) Lists(phone string) ([]CrmStuden, error) {
	list := make([]CrmStuden, 0)
	var err error
	err = Db(0).Table("crm_studen").
		Where("phone = ?", phone).
		Find(&list)
	return list, err
}
